package group

import (
	"api/common"
	"api/pb/group"
	"api/pb/user"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMemberListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMemberListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMemberListLogic {
	return &GetMemberListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetMemberList 获取群成员列表
func (l *GetMemberListLogic) GetMemberList(req *types.GroupMemberListRequest) (resp *types.GroupMemberListResponse, err error) {
	// 1. 请求群成员标识
	memberList, err := l.svcCtx.GroupRPC.GetMemberList(l.ctx,
		&group.MemberListRequest{GroupId: req.GroupID, Offset: req.Offset, Limit: req.Limit})
	if err != nil {
		return nil, err
	}
	// 2. 转换为响应格式
	resp = &types.GroupMemberListResponse{
		Total: memberList.Total,
		Data:  make([]*types.GroupMemberInfo, 0),
	}
	// 3. 获取成员ID列表
	userIDList := make([]int64, 0)
	for _, item := range memberList.Data {
		userIDList = append(userIDList, item.UserId)
	}
	// 4. 获取成员信息
	userList, err := l.svcCtx.UserRPC.GetUserListByIDs(l.ctx, &user.UserListByIDsRequest{Ids: userIDList})
	if err != nil {
		return nil, err
	}
	// 5. 组装字典
	userInfoMap := make(map[int64]*user.UserInfo)
	for _, item := range userList.Data {
		userInfoMap[item.Id] = item
	}
	roleMap := map[int64]string{
		common.ChatGroupMember: "成员",
		common.ChatGroupAdmin:  "管理员",
		common.ChatGroupOwner:  "群主",
	}
	// 6. 转换为响应格式
	for _, item := range memberList.Data {
		resp.Data = append(resp.Data, &types.GroupMemberInfo{
			UserID:   item.UserId,
			UserName: userInfoMap[item.UserId].Name,
			Nick:     item.Nick,
			Role:     item.Role,
			RoleName: roleMap[item.Role],
			JoinTime: item.JoinTime,
		})
	}
	return resp, nil
}
